import { getApiUrl } from '../js/config.prod.js';

// 在页面加载时检查登录状态
document.addEventListener('DOMContentLoaded', () => {
    const user = JSON.parse(localStorage.getItem('user'));
    if (!user || user.role !== 'admin') {
        window.location.href = 'login.html';
        return;
    }
});

// 获取认证头
function getAuthHeaders(additionalHeaders = {}) {
    const token = localStorage.getItem('token');
    return {
        'Authorization': `Bearer ${token}`,
        ...additionalHeaders
    };
}

document.getElementById('uploadForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    const file = document.getElementById('installPackage').files[0];
    const softwareName = document.getElementById('softwareName').value;
    const version = document.getElementById('version').value;
    const description = document.getElementById('description').value;
    const exeName = document.getElementById('exeName').value;

    if (!file || !softwareName || !version) {
        showAlert('请填写必要信息并选择文件', 'error');
        return;
    }

    const chunkSize = 1024 * 1024; // 1MB 分块
    const totalChunks = Math.ceil(file.size / chunkSize);
    const identifier = Date.now().toString();

    // 显示进度条
    const progressContainer = document.getElementById('progressContainer');
    const progressBar = document.getElementById('uploadProgress');
    progressContainer.style.display = 'block';
    progressBar.value = 0;

    try {
        // 上传所有分块
        for (let i = 0; i < totalChunks; i++) {
            const chunk = file.slice(i * chunkSize, (i + 1) * chunkSize);
            const formData = new FormData();
            formData.append('chunk', chunk, 'chunk');

            // 获取认证 token
            const token = localStorage.getItem('token');
            
            const response = await fetch(getApiUrl('uploadChunk'), {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'X-Chunk-Index': i.toString(),
                    'X-Total-Chunks': totalChunks.toString(),
                    'X-Identifier': identifier,
                    'X-Filename': btoa(encodeURIComponent(file.name)),
                    'X-Software-Name': btoa(encodeURIComponent(softwareName)),
                    'X-Version': btoa(encodeURIComponent(version)),
                    'X-Description': btoa(encodeURIComponent(description || '')),
                    'X-Exe-Name': btoa(encodeURIComponent(exeName || ''))
                },
                body: formData
            });

            const contentType = response.headers.get('content-type');
            let errorData;
            
            if (contentType && contentType.includes('application/json')) {
                errorData = await response.json();
            } else {
                const text = await response.text();
                console.error('非 JSON 响应:', text);
                errorData = { message: '服���器返回了非预期的响应' };
            }

            if (!response.ok) {
                throw new Error(errorData.message || '上传失败');
            }

            // 更新进度条
            progressBar.value = ((i + 1) / totalChunks) * 100;

            // 最后一个分块上传完成
            if (i === totalChunks - 1) {
                // 隐藏进度条
                progressContainer.style.display = 'none';
                
                // 显示上传成功提示
                showAlert('上传成功', 'success');
                
                // 清空表单
                document.getElementById('uploadForm').reset();
            }
        }
    } catch (error) {
        console.error('上传错误:', error);
        showAlert(error.message || '上传失败，请重试', 'error');
        progressContainer.style.display = 'none';
    }
});

function showAlert(message, type, duration = 3000) {
    const alertBox = document.getElementById('alertBox');
    if (!alertBox) return;
    
    // 处理多行消息
    if (message.includes('\n')) {
        message = message.split('\n')
            .map(line => line.trim())
            .filter(line => line)
            .join('<br>');
    }
    
    // 清之前的定时器
    if (alertBox.hideTimeout) {
        clearTimeout(alertBox.hideTimeout);
    }
    
    // 重置样式
    alertBox.style.transition = '';
    alertBox.style.opacity = '';
    alertBox.style.transform = '';
    
    alertBox.innerHTML = message;
    alertBox.className = `alert alert-${type}`;
    
    // 显示提示框
    requestAnimationFrame(() => {
        alertBox.classList.add('show');
    });
    
    // 设置隐藏定时器
    alertBox.hideTimeout = setTimeout(() => {
        alertBox.classList.remove('show');
    }, duration);
} 
